package cn.itcast.bos.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class ImageAction extends BaseAction<Object> {

	private static final long serialVersionUID = 1L;
	// 接收参数
	// 上传的文件
	private File imgFile;
	private String imgFileFileName;// 文件名
	private String imgFileContentType;

	@Action(value = "image_upload", results = { @Result(type = "json") })
	public String image_upload() throws IOException {

		System.out.println("文件：" + imgFile);
		System.out.println("文件名：" + imgFileFileName);
		System.out.println("文件类型：" + imgFileContentType);

		// 文件保存的根目录路径，绝对路径D:\eclipse.test\javaee.jiuye.bos2\bos_zhaijisong\bos_management........
		String savePath = ServletActionContext.getServletContext().getRealPath("/") + "upload/";
		// 文件保存的根目录URL，相对路径:::/bos_management/upload/
		String saveUrl = ServletActionContext.getRequest().getContextPath() + "/upload/";

		// 生成随机图片名
		UUID uuid = UUID.randomUUID();
		// 获取文件的后缀名
		String ext = imgFileFileName.substring(imgFileFileName.lastIndexOf("."));
		// 上传的文件为UUID.jpg
		String randomFileName = uuid + ext;

		// 保存图片 (绝对路径)
		File destFile = new File(savePath + "/" + randomFileName);
		System.out.println(destFile.getAbsolutePath());
		FileUtils.copyFile(imgFile, destFile);

		// 通知浏览器文件上传成功
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("error", 0);
		result.put("url", saveUrl + randomFileName); // 返回(相对路径)
		ActionContext.getContext().getValueStack().push(result);

		return SUCCESS;
	}

	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}

	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}

	public void setImgFileContentType(String imgFileContentType) {
		this.imgFileContentType = imgFileContentType;
	}

	// 图片管理
	@Action(value = "image_manage", results = { @Result(type = "json") })
	public String image_manage() {
		// 文件保存的根目录路径，绝对路径
		String rootPath = ServletActionContext.getServletContext().getRealPath("/") + "upload/";
		// 文件保存的根目录URL，相对路径
		String rootUrl = ServletActionContext.getRequest().getContextPath() + "/upload/";

		// 图片扩展名
		String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };

		// 根据path参数，设置各路径和URL
		String path = ServletActionContext.getRequest().getParameter("path") != null
				? ServletActionContext.getRequest().getParameter("path") : "";
		String currentPath = rootPath + path;
		String currentUrl = rootUrl + path;
		String currentDirPath = path;
		String moveupDirPath = "";
		if (!"".equals(path)) {
			String str = currentDirPath.substring(0, currentDirPath.length() - 1);
			moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
		}

		// 排序形式，name or size or type
		String order = ServletActionContext.getRequest().getParameter("order") != null
				? ServletActionContext.getRequest().getParameter("order").toLowerCase() : "name";
		
		// 目录不存在或不是目录
		File currentPathFile = new File(currentPath);

		// 遍历目录取的文件信息
		List<Hashtable<String, Object>> fileList = new ArrayList<Hashtable<String, Object>>();
		if (currentPathFile.listFiles() != null) {
			for (File file : currentPathFile.listFiles()) {
				Hashtable<String, Object> hash = new Hashtable<String, Object>();
				String fileName = file.getName();
				if (file.isDirectory()) {
					hash.put("is_dir", true);
					hash.put("has_file", (file.listFiles() != null));
					hash.put("filesize", 0L);
					hash.put("is_photo", false);
					hash.put("filetype", "");
				} else if (file.isFile()) {
					String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
					hash.put("is_dir", false);
					hash.put("has_file", false);
					hash.put("filesize", file.length());
					hash.put("is_photo", Arrays.<String> asList(fileTypes).contains(fileExt));
					hash.put("filetype", fileExt);
				}
				hash.put("filename", fileName);
				hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
				fileList.add(hash);
			}
		}
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("moveup_dir_path", moveupDirPath);
		result.put("current_dir_path", currentDirPath);
		result.put("current_url", currentUrl);
		result.put("total_count", fileList.size());
		result.put("file_list", fileList);

		ServletActionContext.getContext().getValueStack().push(result);

		return SUCCESS;
	}
}